package cn.itsource.ldj.user.interceptor;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 获取请求头中的token值
        String token = request.getHeader("TOKEN");
        // 根据请求头中的token去redis中查询绑定值
        if (token != null) {
            Object o = redisTemplate.opsForValue().get(token);
            if (o != null) {
                //刷新过去时间
                redisTemplate.opsForValue().set(token, o, 30, TimeUnit.MINUTES);
                return true;
            }
        }

        // 设置响应体和设置编码集
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();

        // 响应数据 {"success": false, "message":"noAuth"}
        writer.println("{\"success\": false, \"msg\":\"noAuth\"}");
        return false;
    }
}
